const express = require('express');
const axios = require('axios');
const { getAvailableAPIs } = require('../config/api-keys');

const router = express.Router();

router.post('/', async (req, res) => {
    try {
        const { prompt, wordCount = 500 } = req.body;

        if (!prompt) {
            return res.status(400).json({ error: '请输入提示词' });
        }

        const availableAPIs = getAvailableAPIs();
        if (availableAPIs.length === 0) {
            return res.status(400).json({ error: '没有配置API密钥' });
        }

        const apiConfig = availableAPIs[0];
        const result = await callAIAPI(apiConfig, prompt, wordCount);
        
        res.json({
            success: true,
            content: result.content,
            apiUsed: apiConfig.name
        });

    } catch (error) {
        console.error('生成失败:', error);
        res.status(500).json({ error: error.message });
    }
});

async function callAIAPI(apiConfig, prompt, wordCount) {
    const response = await axios.post(
        `${apiConfig.baseURL}/chat/completions`,
        {
            model: apiConfig.model,
            messages: [{ role: "user", content: prompt }],
            max_tokens: Math.min(wordCount * 2, 4000)
        },
        {
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${apiConfig.apiKey}`
            }
        }
    );

    return {
        content: response.data.choices[0].message.content
    };
}

module.exports = router;